package model.dao;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import model.Aluno;
import model.Aula;
import model.Professor;

public class AulaDAO {
	
	private EntityManager manager = JPAUtil.getEntityManager();
	
	
	public static AulaDAO getInstance(){
		return new AulaDAO();
	}

	private AulaDAO() {
	}
	
	public void adiciona(Aula aula){
		JPAUtil.iniciaTransacao();
		manager.persist(aula);
		JPAUtil.finalizaTransacao();
	}
	
	public Aula buscaAula(String login){
		Aula aula = manager.find(Aula.class,login);
		return aula;
		
	}
	
	public List<Aula> buscarTodosAula(){
		Query query = manager.createQuery("SELECT p FROM Aula p");
		
		List<Aula> aulas = query.getResultList();
		for (Aula a : aulas){
			for (Aluno a2:a.getAlunos())
				System.out.println(a2.getLogin());
		}
		return aulas;
	}
	
	public List<Aula> buscarTodasAulasPorAluno(String login){
		Aluno aluno = AlunoDAO.getInstance().buscaAluno(login);
		Query query = manager.createQuery("SELECT p FROM Aula p INNER JOIN p.alunos a Where a.id = ?");
		query.setParameter(1, aluno.getId());
		return (List<Aula>)query.getResultList();
	}
	
	public List<Aula> buscarTodasAulasPorProfessor(String login){
		Professor professor = ProfessorDAO.getInstance().buscaProfessor(login);
				
		List<Aula> aulas = null;
		try {
			aulas = AulaDAO.getInstance().buscarTodosAula();			
		} catch (Exception e) {

		}
		if (!aulas.isEmpty()){
			Query query = manager.createQuery("SELECT a FROM Aula a  WHERE  a.disciplinas.professor.id = ?");
			query.setParameter(1, professor.getId());
			aulas = query.getResultList();
		}
		return aulas;
	}
	
	public List<Aula> buscarTodasAulasPorData(Date data){
		Query query = manager.createQuery("SELECT p FROM Aula p  Where p.data = current_date()");
		List<Aula> aulas = query.getResultList();
		
		for (Aula a : aulas){
			System.out.println(a.getConteudo());
		}
		return aulas;
	}
}
